<template>
  <div class="consultation-detail-view">
    <div class="detail-header">
      <el-button @click="router.back()" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>返回
      </el-button>
      <h1 class="detail-title">{{ consultation.title }}</h1>
      <el-tag :type="getStatusType(consultation.status)" size="large">
        {{ getStatusText(consultation.status) }}
      </el-tag>
      <!-- 显示评分 -->
      <div v-if="consultation.status === 'completed' && consultation.rating" class="rating-display">
        <el-rate v-model="consultation.rating" disabled show-score text-color="#ff9900" />
      </div>
    </div>

    <!-- 咨询基本信息 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>咨询信息</span>
        </div>
      </template>

      <div class="info-grid">
        <div class="info-item">
          <label>咨询类型：</label>
          <span>{{ consultation.category }}</span>
        </div>
        <div class="info-item">
          <label>咨询用户：</label>
          <span>{{ consultation.clientName }}</span>
        </div>
        <div class="info-item">
          <label>负责律师：</label>
          <span>{{ consultation.lawyerName || '待分配' }}</span>
        </div>
        <div class="info-item">
          <label>创建时间：</label>
          <span>{{ formatDate(consultation.createdAt) }}</span>
        </div>
        <div class="info-item">
          <label>最后更新：</label>
          <span>{{ formatDate(consultation.updatedAt) }}</span>
        </div>
        <!-- 显示评分信息 -->
        <div v-if="consultation.status === 'completed'" class="info-item full-width">
          <label>用户评分：</label>
          <span>
            <el-rate v-model="consultation.rating" disabled show-score text-color="#ff9900" />
          </span>
        </div>
      </div>

      <div class="description-section">
        <label>问题描述：</label>
        <p>{{ consultation.description }}</p>
      </div>

      <!-- 显示用户评价 -->
      <div v-if="consultation.status === 'completed' && consultation.review" class="review-section">
        <label>用户评价：</label>
        <div class="review-content">
          <p>{{ consultation.review }}</p>
          <div class="review-meta">
            <span class="review-time">评价时间：{{ formatDate(consultation.updatedAt) }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 消息区域 -->
    <el-card class="messages-card">
      <template #header>
        <div class="card-header">
          <span>咨询对话</span>
        </div>
      </template>

      <div class="messages-container">
        <div v-if="messagesLoading" class="loading-messages">
          <el-skeleton :rows="3" animated />
        </div>

        <div v-else-if="messages.length === 0" class="empty-messages">
          <el-empty description="暂无消息记录" />
        </div>

        <div v-else class="messages-list">
          <div
            v-for="message in messages"
            :key="message.id"
            :class="[
              'message-item',
              isCurrentUserMessage(message) ? 'own-message' : 'other-message',
            ]"
          >
            <div class="message-avatar">
              <el-avatar :size="40" :src="getAvatar(message)" />
            </div>
            <div class="message-content">
              <div class="message-header">
                <span class="sender-name">{{ getSenderName(message) }}</span>
              </div>
              <div class="message-bubble">
                <div v-if="message.messageType === 'text'" class="text-content">
                  {{ message.content }}
                </div>
                <div v-else-if="message.messageType === 'file'" class="file-content">
                  <el-icon><Document /></el-icon>
                  <a :href="message.fileUrl" target="_blank">查看文件</a>
                </div>
                <div class="message-time">
                  {{ formatTime(message.createdAt) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <!-- 待接单状态：创建者可以取消咨询 -->
      <el-button
        v-if="consultation.status === 'pending' && isConsultationCreator"
        type="warning"
        @click="cancelConsultation"
      >
        取消咨询
      </el-button>

      <!-- 律师接单按钮 -->
      <el-button
        v-if="isLawyer && consultation.status === 'pending'"
        type="primary"
        @click="acceptConsultation"
      >
        <el-icon><Check /></el-icon>接取咨询
      </el-button>

      <!-- 进行中状态：创建者可以继续咨询或完成咨询 -->
      <template v-if="consultation.status === 'active' && isConsultationAcceptor">
        <el-button type="primary" @click="enterChat">
          <el-icon><ChatDotRound /></el-icon>继续咨询
        </el-button>
      </template>

      <!-- 进行中状态：创建者可以继续咨询或完成咨询 -->
      <template v-if="consultation.status === 'active' && isConsultationCreator">
        <el-button type="primary" @click="enterChat">
          <el-icon><ChatDotRound /></el-icon>继续咨询
        </el-button>
        <el-button type="success" @click="completeConsultation">
          <el-icon><Check /></el-icon>完成咨询
        </el-button>
      </template>

      <!-- 已完成状态：创建者可以评价（如果未评价） -->
      <el-button
        v-if="consultation.status === 'completed' && !consultation.rating && isConsultationCreator"
        type="success"
        @click="showReviewDialog = true"
      >
        <el-icon><Star /></el-icon>评价咨询
      </el-button>
    </div>

    <!-- 评价对话框 -->
    <el-dialog v-model="showReviewDialog" title="咨询评价" width="500px">
      <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef">
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="reviewForm.rating" show-text />
        </el-form-item>
        <el-form-item label="反馈内容" prop="review">
          <el-input
            v-model="reviewForm.review"
            type="textarea"
            :rows="4"
            placeholder="请分享您的咨询体验..."
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showReviewDialog = false">取消</el-button>
        <el-button type="primary" @click="submitReview">提交评价</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, inject, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userInfoStore } from '@/stores/userinfo'
import { ArrowLeft, ChatDotRound, Document, Star } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const api = inject('$api')
const userStore = userInfoStore()

const consultationId = ref(route.params.id)
const consultation = ref({})
const messages = ref([])
const messagesLoading = ref(false)
const showReviewDialog = ref(false)
const userInfoMap = ref({})

const reviewForm = ref({
  rating: 5,
  review: '',
})

const reviewRules = {
  rating: [{ required: true, message: '请选择评分', trigger: 'change' }],
  review: [{ required: true, message: '请输入反馈内容', trigger: 'blur' }],
}

// 添加计算属性判断当前用户是否为律师
const isLawyer = computed(() => {
  return userStore.user?.role === 'LAWYER'
})

// 添加接单方法
const acceptConsultation = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要接取咨询 "${consultation.value.title}" 吗？接取后您将成为负责律师。`,
      '确认接单',
      {
        type: 'warning',
        confirmButtonText: '确认接单',
        cancelButtonText: '取消',
      },
    )

    const response = await api.consultation.acceptConsultation(
      consultationId.value,
      userStore.user.id,
    )

    if (response.code === 200) {
      ElMessage.success('接单成功！')
      // 刷新详情数据
      fetchConsultationDetail()
    } else {
      ElMessage.error(response.message || '接单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('接单失败，请重试')
    }
  }
}

// 计算属性：判断当前用户是否为咨询接单者
const isConsultationAcceptor = computed(() => {
  return consultation.value.lawyerId === userStore.user?.id
})

// 计算属性：判断当前用户是否为咨询创建者
const isConsultationCreator = computed(() => {
  return consultation.value.clientId === userStore.user?.id
})

// 判断是否为当前用户的消息
const isCurrentUserMessage = (message) => {
  // // 如果有登录用户，比较senderId
  // if (userStore.user?.id) {
  //   return message.senderId === userStore.user.id
  // }
  // 未登录情况下，根据senderType判断
  return message.senderType === 'client'
}

const fetchConsultationDetail = async () => {
  try {
    const response = await api.consultation.getConsultationDetail(consultationId.value)
    if (response.code === 200) {
      consultation.value = response.data
    } else {
      ElMessage.error(response.message || '获取咨询详情失败')
    }
  } catch (error) {
    console.error('获取咨询详情失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

const fetchMessages = async () => {
  try {
    messagesLoading.value = true
    const response = await api.consultation.getMessages(consultationId.value)
    if (response.code === 200) {
      messages.value = response.data
      await fetchUserInfo()
    }
  } catch (error) {
    console.error('获取消息失败:', error)
  } finally {
    messagesLoading.value = false
  }
}

// 获取用户公开信息
const fetchUserInfo = async () => {
  try {
    // 提取所有消息中的发送者ID
    const senderIds = [...new Set(messages.value.map((msg) => msg.senderId))]

    if (senderIds.length > 0) {
      const response = await api.user.getUsersPublicInfoBatch(senderIds)
      if (response.code === 200) {
        // 将用户信息转换为映射表
        response.data.forEach((user) => {
          userInfoMap.value[user.id] = user
        })
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    active: 'primary',
    completed: 'success',
    cancelled: 'info',
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待接单',
    active: '进行中',
    completed: '已完成',
    cancelled: '已取消',
  }
  return texts[status] || status
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

const formatTime = (dateString) => {
  return new Date(dateString).toLocaleTimeString()
}

const getAvatar = (message) => {
  const userInfo = userInfoMap.value[message.senderId]
  if (userInfo && userInfo.avatarUrl) {
    return userInfo.avatarUrl
  }

  // 默认头像
  return message.senderType === 'lawyer'
    ? '@/default-lawyer-avatar.png'
    : '/default-user-avatar.png'
}

const getSenderName = (message) => {
  const userInfo = userInfoMap.value[message.senderId]

  // 如果有用户信息，使用真实姓名
  if (userInfo && userInfo.realName) {
    return userInfo.realName
  }

  // 判断是否为当前用户
  if (isCurrentUserMessage(message)) {
    return '我'
  }

  // 默认显示
  return message.senderType === 'lawyer' ? '律师' : '用户'
}

const enterChat = () => {
  router.push(`/consultation/${consultationId.value}/chat`)
}

// 取消咨询
const cancelConsultation = async () => {
  try {
    await ElMessageBox.confirm('确定要取消这个咨询吗？', '提示', {
      type: 'warning',
    })

    const response = await api.consultation.updateConsultationStatus(
      consultationId.value,
      'cancelled',
    )
    if (response.code === 200) {
      ElMessage.success('咨询已取消')
      consultation.value.status = 'cancelled'
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消咨询失败')
    }
  }
}

// 完成咨询（用户视角）
const completeConsultation = async () => {
  try {
    await ElMessageBox.confirm('确定要完成这个咨询吗？完成后将无法继续发送消息。', '提示', {
      type: 'warning',
    })

    const response = await api.consultation.updateConsultationStatus(
      consultationId.value,
      'completed',
    )
    if (response.code === 200) {
      ElMessage.success('咨询已完成')
      consultation.value.status = 'completed'
      // 完成后自动打开评价对话框
      showReviewDialog.value = true
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('完成咨询失败')
    }
  }
}

const submitReview = async () => {
  try {
    const response = await api.consultation.submitReview(consultationId.value, reviewForm.value)
    if (response.code === 200) {
      ElMessage.success('评价提交成功')
      showReviewDialog.value = false
      consultation.value.rating = reviewForm.value.rating
      consultation.value.review = reviewForm.value.review
      // 重置评价表单
      reviewForm.value.rating = 5
      reviewForm.value.review = ''
    }
  } catch (error) {
    ElMessage.error('提交评价失败')
  }
}

onMounted(() => {
  fetchConsultationDetail()
  fetchMessages()
})
</script>

<style scoped>
.consultation-detail-view {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.back-btn {
  margin-right: auto;
}

.detail-title {
  margin: 0;
  color: #1a3a5f;
  flex: 1;
  min-width: 200px;
}

.rating-display {
  display: flex;
  align-items: center;
}

.rating-display :deep(.el-rate) {
  margin-top: -3px;
}

.info-card,
.messages-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: flex-start;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-item label {
  font-weight: bold;
  min-width: 80px;
  color: #666;
  margin-right: 10px;
}

.info-item span {
  flex: 1;
}

.description-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.description-section label {
  font-weight: bold;
  color: #666;
  display: block;
  margin-bottom: 10px;
}

.review-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.review-section label {
  font-weight: bold;
  color: #666;
  display: block;
  margin-bottom: 10px;
}

.review-content {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #1a3a5f;
}

.review-content p {
  margin: 0 0 10px 0;
  line-height: 1.6;
  color: #333;
}

.review-meta {
  display: flex;
  justify-content: flex-end;
}

.review-time {
  font-size: 0.8rem;
  color: #999;
}

.messages-container {
  max-height: 400px;
  overflow-y: auto;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message-item {
  display: flex;
  gap: 10px;
}

.own-message {
  flex-direction: row-reverse;
}

.message-bubble {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 18px;
  position: relative;
}

.own-message .message-bubble {
  background: #1a3a5f;
  color: white;
}

.other-message .message-bubble {
  background: #f0f0f0;
  color: #333;
}

.message-time {
  font-size: 0.8rem;
  opacity: 0.7;
  margin-top: 5px;
}

.file-content {
  display: flex;
  align-items: center;
  gap: 5px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 30px;
}

.loading-messages {
  padding: 20px 0;
}

.empty-messages {
  padding: 40px 0;
  text-align: center;
}
</style>
